﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using CutAways.Modeling;

namespace CutAways
{
	partial class ObjectBrowserForm : Form
	{
		private MainForm mainForm;
		private Model model;
		public event EventHandler Change;

		public ObjectBrowserForm(MainForm mainForm)
		{
			InitializeComponent();
			this.mainForm = mainForm;
			this.model = this.mainForm.MyGLControl.Model;

			model.SelectedObjectChanged += model_SelectedObjectChanged;

			if (!string.IsNullOrEmpty(model.Name))
				this.Text = model.Name + " - Object browser";
			fillListBox();
		}

		protected override void OnClosed(EventArgs e)
		{
			mainForm.SetProgramMode(ProgramMode.Illustrator);
			this.model.SelectedObjectChanged -= model_SelectedObjectChanged;
			base.OnClosed(e);
		}

		void model_SelectedObjectChanged(object sender, EventArgs e)
		{
			checkedListBoxObjects.SelectedItem = model.SelectedObject;
		}

		private void fillListBox()
		{
			foreach (GeometricObject o in model.Objects)
				checkedListBoxObjects.Items.Add(o, o.Visible);
			checkedListBoxObjects.SelectedItem = model.SelectedObject;
		}

		private void checkedListBoxObjects_ItemCheck(object sender, ItemCheckEventArgs e)
		{
			if (e.NewValue == CheckState.Checked)
				((GeometricObject)checkedListBoxObjects.Items[e.Index]).Visible = true;
			else if (e.NewValue == CheckState.Unchecked)
				((GeometricObject)checkedListBoxObjects.Items[e.Index]).Visible = false;

			if (Change != null)
				Change(this, EventArgs.Empty);
		}

		private void checkedListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
		{
			propertyGridObject.SelectedObject = checkedListBoxObjects.SelectedItem;
			model.SelectedObject = checkedListBoxObjects.SelectedItem as GeometricObject;

			if (model.SelectedObject == null)
				buttonEditBoundingBox.Enabled = false;
			else
				buttonEditBoundingBox.Enabled = true;

			if (mainForm.MyGLControl.ProgramMode == ProgramMode.EditBoundingBox)
			{
				mainForm.MyGLControl.WorkObject = null;
				mainForm.SetProgramMode(ProgramMode.Illustrator);
			}
		}


		private void buttonOK_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void buttonAdjustAxes_Click(object sender, EventArgs e)
		{
			mainForm.MyGLControl.WorkObject = (GeometricObject)checkedListBoxObjects.SelectedItem;
			mainForm.SetProgramMode(ProgramMode.EditBoundingBox);

			buttonOK.Focus();
			mainForm.Focus();
		}
		
	}
}
